package example;

import example.SwingWorker;
import my.com.sunway.bean.*;
import my.com.sunway.event.*;
import my.com.sunway.listener.*;
import my.com.sunway.util.*;
import net.sf.hibernate.*;
import org.apache.log4j.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*;
import org.jdesktop.swingx.*;

public class F0911Browser extends JFrame implements ActionListener, HibernateEventListener{
    private static Logger logger = Logger.getLogger(F0911Browser.class);
    private DefaultTableModel tblmF0911 = null;
    private JTable tblF0911 = null;
    private JButton btnLookup = null;
    private JXDatePicker dfDate = null;
    public static JLabel lblStatus = null;
    private static HibernateWorker worker = null;
    private JScrollPane jsTblPane = null;
    private Session session = null;
    public static JPanel jpnlMain = null;
    private JProgressBar progressBar = null;
    private final int max_items_per_page = 20;
    private int current_item = 0;
    private static long parse_date = 0;
    private SimpleDateFormat sdf_yyyyMMdd = null;
    
    public F0911Browser(){
        super("P0911");
        init();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
    }
    
    public void init(){
        sdf_yyyyMMdd = new SimpleDateFormat("yyyy/MM/dd");
        Container ctnParent = this.getContentPane();
        jpnlMain = new JPanel(new BorderLayout());
        JPanel jpnlInput = new JPanel(new GridLayout(1,3));
        
        btnLookup = new JButton("Lookup");
        btnLookup.addActionListener(this);
        dfDate = new JXDatePicker();
        lblStatus = new JLabel("");
        //progressBar = new JProgressBar();
        
        //lblStatus.setVisible(false);
        
        ResourceBundle bundle = ResourceBundle.getBundle("preliminary_settings", Locale.ENGLISH);
        
        String[] f0911_alias = RegexCSVUtil.splitCSV(",",
                bundle.getString("my.com.sunway.bean.F0911.keys"));
        String[] f0911_columnNames = new String[f0911_alias.length];
        
        for(int col=0; col<f0911_columnNames.length; col++){
            f0911_columnNames[col] = getColumnNameFromAlias("gl",f0911_alias[col]);
        }
        
        tblmF0911 = new DefaultTableModel(f0911_columnNames,0);
        tblF0911 = new JTable(tblmF0911);
        tblF0911.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
        jsTblPane = new JScrollPane(tblF0911);
        
        jpnlInput.add(new JLabel("G/L Date:"));
        jpnlInput.add(dfDate);
        jpnlInput.add(btnLookup);
        jpnlMain.add(jpnlInput,BorderLayout.NORTH);
        jpnlMain.add(jsTblPane,BorderLayout.CENTER);
        jpnlMain.add(lblStatus,BorderLayout.SOUTH);
        //jpnlMain.add(progressBar,BorderLayout.SOUTH);
        ctnParent.add(jpnlMain);
    }
    
    public void actionPerformed(ActionEvent event){
        Object source = event.getSource();
        if(source==btnLookup){
            String input_date = sdf_yyyyMMdd.format(dfDate.getDate());
            
            if(input_date.matches("[0-9]{4}/[0-9]{2}/[0-9]{2}")){
                logger.debug("paramValue = <date>");
                try{
                    Date date = sdf_yyyyMMdd.parse(input_date);
                    SimpleDateFormat sdf_yyyDDD = new SimpleDateFormat("yyyyDDD");
                    String formatted_date = sdf_yyyDDD.format(date);
                    parse_date = Long.parseLong(formatted_date)-1900001;
                    
                    btnLookup.setEnabled(false);
                }catch(Exception ex){
                }
                
                SwingWorker swingworker = new SwingWorker() {
                    public Object construct() {
                        findF0911(parse_date);
                        return null;
                    }
                    
                    public void finished() {
                        //
                    }
                };
                swingworker.start();
            }else{
                JOptionPane.showMessageDialog(null,
                        "INFO",
                        "invalid date format: yyyy/MM/dd",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
    
    public String getColumnNameFromAlias(String prefix, String alias){
        String columnName = alias;
        Query query = null;
        Object obj = null;
        F9202 f9202 = null;
        
        try{
            String hsql = "from my.com.sunway.bean.F9202 where frdtai=:alias";
            session = HibernateUtil.currentSession();
            query = session.createQuery(hsql);
            query.setString("alias",alias.substring(prefix.length()).toUpperCase());
            obj = query.list().get(0);
            logger.info("F9202 = "+obj);
            if(obj instanceof F9202){
                f9202 = (F9202)obj;
                columnName = f9202.getFrch1().trim()+" "+f9202.getFrch2().trim();
            }
        }catch(Exception ex){
            logger.error("",ex);
        }finally{
            return columnName;
        }
    }
    
    public void findF0911(long parse_date){
        ScrollableResults results = null;
        String queryName = null;
        Query query = null;
        
        try{
            if(worker==null){
                session = HibernateUtil.currentSession();
                
                queryName = "my.com.sunway.query.F0911.getQueryByGLDGJ";
                //queryName = "my.com.sunway.query.F0911.getQueryByHeaderOnly";
                query = session.getNamedQuery(queryName);
                query.setLong("param",parse_date);
                results = query.scroll();
                worker = new HibernateWorker(results,max_items_per_page,"my.com.sunway.bean.F0911");
                worker.addHibernateEventListener(this);
                
                
                lblStatus.setText("loading ...");
                ImageIcon icon = createImageIcon("resources/loading.gif","loading");
                logger.info("icon = "+icon);
                //lblStatus = new JLabel("loading ...");
                lblStatus.setIcon(icon);
                icon.setImageObserver(lblStatus);
                worker.run();
                
                //SwingUtilities.invokeLater(worker);
            }
        }catch(Exception ex){
            //logger.error(""+ex);
        }finally{
            // do nothing
        }
    }
    
    public void dataRowFetched(HibernateEvent event){
        Object obj = event.getSource();
        F0911 f0911 = null;
        SimpleDateFormat sdf_yyyyDDD = new SimpleDateFormat("yyyyDDD");
        
        //logger.info("data came in ... "+event.getSource());
        //lblStatus.setText("loading "+(((new Date().getTime()/2)==0)?"..":"..."));
        try{
            if(obj instanceof F0911){
                f0911 = (F0911)obj;
                Vector rowData = new Vector();
                rowData.addElement(f0911.getGldct());
                rowData.addElement(f0911.getGldoc());
                rowData.addElement(f0911.getGlkco());
                long julian_date = f0911.getGldgj().longValue();
                String print_date = sdf_yyyyMMdd.format(sdf_yyyyDDD.parse(""+(julian_date+1900001)));
                rowData.addElement(print_date);
                rowData.addElement(f0911.getGljeln());
                rowData.addElement(f0911.getGllt());
                rowData.addElement(f0911.getGlextl());
                tblmF0911.addRow(rowData);
                int row = tblF0911.getRowCount() - 1;
                tblF0911.changeSelection(row, row, false, false);
                tblF0911.requestFocusInWindow();
            }else{
                //logger.info("object not printed: "+obj);
            }
        }catch(Exception ex){
            logger.error("",ex);
        }
        //progressBar.setValue(i);
        
    }
    
    public void transactionCompleted(HibernateEvent event){
        logger.info("fetching done ...");
        //HibernateUtil.closeSession();
        //progressBar.setValue(max_items_per_page);
        //double remainder = current_item/max_items_per_page;
        //progressBar.setValue((int)(remainder*100));
        current_item = 0;
        worker = null;
        btnLookup.setEnabled(true);
        lblStatus.setText("");
        lblStatus.setIcon(null);
        //lblStatus.setVisible(false);
    }
    
    public static final ImageIcon createImageIcon(String path,String description) {
        ClassLoader cldr = F0911Browser.class.getClassLoader();
        java.net.URL imgURL = cldr.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL, description);
        } else {
            logger.error("Couldn't find file: " + path);
            return null;
        }
    }
    
    public static void main(String[] args){
        F0911Browser app = new F0911Browser();
        
        app.setVisible(true);
    }
}
